package com.zzzzzz.app.topic.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.zzzzzz.app.topic.NoSuchTopicException;
import com.zzzzzz.app.topic.model.po.Topic;
import com.zzzzzz.core.dao.BaseDao;
import com.zzzzzz.core.exception.SystemException;

@Repository
public class TopicDao extends BaseDao{
	
	private static final String ADD = "insert into topic(title, content, create_date, modified_date, user_id) values (:title, :content, :createDate, :modifiedDate, :userId)";
	private static final String EDIT = "update topic set title = :title, content = :content, modified_date = :modifiedDate where topic_id = :topicId";
	private static final String FIND_BY_ID = "select * from topic where topic_id = ?";

	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Topic exists with the primary key ";
	
	protected class TopicRowMapper implements RowMapper<Topic> {
//		@Override
		public Topic mapRow(ResultSet rs, int rn) throws SQLException {
			Topic topic = new Topic();
			topic.setTopicId(rs.getLong("topic_id"));
			topic.setTitle(rs.getString("title"));
			topic.setContent(rs.getString("content"));
			topic.setCreateDate(rs.getTimestamp("create_date"));
			topic.setModifiedDate(rs.getTimestamp("modified_date"));
			topic.setUserId(rs.getLong("user_id"));
			return topic;
		}
	}
	
	public void add(Topic topic) throws SystemException {
		Long id = updateForLongKey(ADD, topic);
		topic.setTopicId(id);
	}

	public void edit(Topic topic) throws SystemException {
		update(EDIT, topic);
	}
	
	public Topic findById(Long id) throws NoSuchTopicException, SystemException {
//		return jdbcTemplate.queryForObject(FIND_BY_ID, new TopicRowMapper(), id);
		Topic topic = null;
		try{
			List<Topic> topics = findList(FIND_BY_ID, new TopicRowMapper(), id);
			if(topics != null && topics.size()>0) {
				topic = topics.get(0);
			}
		}catch(Exception e) {
			throw processException(e);
		}
		if(topic == null) {
			throw new NoSuchTopicException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + id);
		}
		return topic;
	}
	
	
}
